package edu.nf.redismqes.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import edu.nf.redismqes.mappers.newsMapper;
import edu.nf.redismqes.model.docmentt.NewDoc;
import edu.nf.redismqes.model.entity.New;
import edu.nf.redismqes.service.factory.NewHandlerFactory;
import edu.nf.redismqes.service.handler.NewHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpRejectAndDontRequeueException;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import edu.nf.redismqes.common.config.RabbitConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;

/**
 * @ Author bin
 * @ Create  2025/10/21 下午4:11
 * 发布新闻消费者
 **/
@Slf4j
@Service
public class newConsumerService {
    @Autowired
    private NewHandlerFactory factory;
    @Autowired
    private ObjectMapper mapper = new ObjectMapper();

    /**
     * 接收消息
     * @param New
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = RabbitConfig.QUEUE_NAME, durable = "false"),
            exchange = @Exchange(name = RabbitConfig.EXCHANGE_NAME, type = ExchangeTypes.DIRECT),
            key = RabbitConfig.ROUTING_KEY))
    public void receive(Message message){
        String action = (String)message.getMessageProperties().getHeaders().get("action");
        String body = new String(message.getBody(), StandardCharsets.UTF_8);

        try {
            New aNew = mapper.readValue(body, New.class);
            NewHandler handler = factory.getHandler(action);

            if(handler != null){
                handler.handle(aNew);
            }else {
//                log.error("没有对应的处理类");
                throw new RuntimeException("没有对应的处理类");
            }
        } catch (Exception e) {
//            log.error("消息处理失败：{}",e.getMessage(),e);
            throw new AmqpRejectAndDontRequeueException("处理失败，不重回队列", e);
        }
    }

    /**
     * 转换器
     * */
//    private NewDoc convertToDoc(New news) {
//        NewDoc doc = new NewDoc();
//        doc.setId(news.getId());
//        doc.setTitle(news.getTitle());
//        doc.setAuthor(news.getAuthor());
//        doc.setType(news.getType());
//        doc.setContent(news.getContent());
//        doc.setPublicshDate(news.getPublicshDate());
//        return doc;
//    }
}
